package com.xzx.study;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MenuActivity extends AppCompatActivity {

    private Button btn_context_menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        btn_context_menu = findViewById(R.id.btn_context_menu);
        btn_context_menu.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                // 方式一：纯编码 group 不关心可以传none
                menu.add(Menu.NONE, 1, Menu.NONE, "添加");
                menu.add(Menu.NONE, 2, Menu.NONE, "删除");

                // 方式二：menu文件的方式
//                MenuInflater menuInflater = getMenuInflater();
//                menuInflater.inflate(R.menu.menu_option, menu);
            }
        });
    }

    // 可选菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 方式一：纯编码 group 不关心可以传none
//        menu.add(Menu.NONE, 1, Menu.NONE, "添加");
//        menu.add(Menu.NONE, 2, Menu.NONE, "删除");

        // 方式二：menu文件的方式
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_option, menu);
        return super.onCreateOptionsMenu(menu);
    }

    // 可选菜单点击
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Toast.makeText(this, item.getItemId() + item.getTitle().toString(), 0).show();
        return super.onOptionsItemSelected(item);
    }

    // 上下文菜单
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        Toast.makeText(this, item.getItemId() + item.getTitle().toString(), 0).show();
        return super.onContextItemSelected(item);
    }
}
